/**
 * $RCSfile: Newline.java,v $
 * $Revision: 1.7 $
 * $Date: 2001/09/05 15:49:25 $
 *
 * Copyright (C) 1999-2001 CoolServlets, Inc. All rights reserved.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */

package com.jivesoftware.forum.filter;

import java.util.*;

import com.jivesoftware.forum.*;
import com.jivesoftware.util.*;

/**
 * A ForumMessageFilter that converts newline characters into HTML &lt;br&gt; tags.
 * This filter should only be run after any HTML stripping filters.
 */
public class Newline extends ForumMessageFilter {

    private static final char[] BR_TAG = "<BR>".toCharArray();

    /**
     * Clones a new filter that will have the same properties and that
     * will wrap around the specified message.
     *
     * @param message the ForumMessage to wrap the new filter around.
     */
    public ForumMessageFilter clone(ForumMessage message) {
        Newline filter = new Newline();
        filter.message = message;
        return filter;
    }

    public boolean isCacheable() {
        return true;
    }

    /**
     * Returns the body of the message with newline characters converted to
     * HTML &ltbr&gt tags.
     *
     * @return the body with newline characters converted to HTML.
     */
    public String getBody() {
        if (message.getBody() == null) {
            return null;
        }
        return convertNewlines(message.getBody());
    }

    /**
     * Replaces newline characters with the HTML equivalent.
     *
     * @param input the text to be converted.
     * @return the input string with newline characters replaced with HTML
     *      newline tags..
     */
    private static String convertNewlines(String input) {
        char [] chars = input.toCharArray();
        int cur = 0;
        int len = chars.length;
        StringBuffer buf = new StringBuffer(len);
        // Loop through each character lookin for newlines.
        for (int i=0; i<len; i++) {
            // If we've found a Unix newline, add BR tag.
            if (chars[i]=='\n') {
                buf.append(chars, cur, i-cur).append(BR_TAG);
                cur = i+1;
            }
            // If we've found a Windows newline, add BR tag.
            else if (chars[i]=='\r' && i<len-1 && chars[i+1]=='\n') {
                buf.append(chars, cur, i-cur).append(BR_TAG);
                i++;
                cur = i+1;
            }
        }
        // Add whatever chars are left to buffer.
        buf.append(chars, cur, len-cur);
        return buf.toString();
    }
}